package com.kk.crowd.service.impl;

import com.kk.crowd.entity.po.MemberConfirmInfoPO;
import com.kk.crowd.entity.po.MemberLaunchInfoPO;
import com.kk.crowd.entity.po.ProjectPO;
import com.kk.crowd.entity.po.ReturnPO;
import com.kk.crowd.entity.vo.*;
import com.kk.crowd.mapper.*;
import com.kk.crowd.service.api.ProjectProviderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Transactional(readOnly = true)
@Service
public class ProjectProviderServiceImpl implements ProjectProviderService {

    @Autowired
    private ProjectPOMapper projectPOMapper;

    @Autowired
    private ProjectItemPicPOMapper projectItemPicPOMapper;

    @Autowired
    private MemberLaunchInfoPOMapper memberLaunchInfoPOMapper;

    @Autowired
    private ReturnPOMapper returnPOMapper;

    @Autowired
    private MemberConfirmInfoPOMapper memberConfirmInfoPOMapper;

    // 对方法取消只读，设置事务传播行为  readOnly = false(默认是false)
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class, readOnly = false)
    public void saveProject(ProjectVO projectVO, Integer memberId) {
        // 一、保存ProjectPO对象
        // 1.创建空的ProjectPO对象
        ProjectPO projectPO = new ProjectPO ( );

        // 2.把ProjectVO的属性复制到ProjectPO中
        BeanUtils.copyProperties (projectVO, projectPO);

        // 把memberId设置到projectPO中
        projectPO.setMemberid (memberId);

        // 生成创建时间存入
        String createdate = new SimpleDateFormat ("yyyy-MM-dd").format (new Date ( ));
        projectPO.setCreatedate (createdate);

        // status设置成0，表示即将开始
        projectPO.setStatus (0);

        // 3.保存projectPO
        // 为了能够取得到 projectPO保存后自增的主键值，需要到 ProjectPOMapping.xml 进行相应设置:
        // <insert id="insertSelective" useGeneratedKeys="true" keyProperty="id" ...
        projectPOMapper.insertSelective (projectPO);  // insertSelective 和 inset 不同的是 前者为有选择性保存（就是非空判断）

        // 4.从projectPO对象获取自增主键
        Integer projectId = projectPO.getId ( );

        // 二、保存项目分类的关联信息
        // 1.从ProjectVO对象中获取typeIdList
        List<Integer> typeIdList = projectVO.getTypeIdList ( );
        projectPOMapper.insertTypeRelationship (typeIdList, projectId);

        // 三、保存项目、标签的关联关系信息
        List<Integer> tagIdList = projectVO.getTagIdList ( );
        projectPOMapper.insertTagRelationship (tagIdList, projectId);

        // 四、保存项目中详情图片路径信息
        List<String> detailPicturePathList = projectVO.getDetailPicturePathList ( );
        projectItemPicPOMapper.insertPathList (projectId, detailPicturePathList);

        // 五、保存项目发起人信息
        MemberLauchInfoVO memberLauchInfoVO = projectVO.getMemberLauchInfoVO ( );
        MemberLaunchInfoPO memberLaunchInfoPO = new MemberLaunchInfoPO ( );
        BeanUtils.copyProperties (memberLauchInfoVO, memberLaunchInfoPO);
        memberLaunchInfoPO.setMemberid (memberId);
        memberLaunchInfoPOMapper.insert (memberLaunchInfoPO);

        // 六、保存项目回报信息
        List<ReturnVO> returnVOList = projectVO.getReturnVOList ( );
        List<ReturnPO> returnPOList = new ArrayList<ReturnPO> ( );

        for (ReturnVO returnVO : returnVOList) {
            ReturnPO returnPO = new ReturnPO ( );
            BeanUtils.copyProperties (returnVO, returnPO);
            returnPOList.add (returnPO);
        }

        returnPOMapper.insertReturnPOBatch (returnPOList, projectId);

        // 七、保存项目确认信息
        MemberConfirmInfoVO memberConfirmInfoVO = projectVO.getMemberConfirmInfoVO ( );
        MemberConfirmInfoPO memberConfirmInfoPO = new MemberConfirmInfoPO ( );
        BeanUtils.copyProperties (memberConfirmInfoVO, memberConfirmInfoPO);
        memberConfirmInfoPO.setMemberid (memberId);
        memberConfirmInfoPOMapper.insert (memberConfirmInfoPO);
    }

    public List<PortalTypeVO> getPortalTypeVO() {
        return projectPOMapper.selectPortalTypeVOList ( );
    }

    // 首页点击的项目详情
    public DetailProjectVO getDetailProjectVO(Integer projectId) {
        // 1.查询得到 DetailProjectVO 对象
        DetailProjectVO detailProjectVO = projectPOMapper.selectDetailProjectVO (projectId);
        // 2.根据 status 确定 statusText
        Integer status = detailProjectVO.getStatus ( );

        switch (status) {
            case 0:
                detailProjectVO.setStatusText ("审核中");
                break;
            case 1:
                detailProjectVO.setStatusText ("众筹中");
                break;
            case 2:
                detailProjectVO.setStatusText ("众筹成功");
                break;
            case 3:
                detailProjectVO.setStatusText ("已关闭");
                break;
            default:
                break;
        }

        // 3.根据 deployeDate 计算 lastDay
        // 格式：2020-10-15
        String deployDate = detailProjectVO.getDeployDate ( );

        // 获取当前日期
        Date currentDay = new Date ( );

        // 把众筹日期解析成 Date 类型
        SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd");

        // 动态计算出 距离众筹结束时间
        try {
            Date deployDay = format.parse (deployDate);

            // 获取当前当前日期的时间戳
            long currentTimeStamp = currentDay.getTime ( );

            // 获取众筹日期的时间戳
            long deployTimeStamp = deployDay.getTime ( );

            // 两个时间戳相减计算当前已经过去的时间
            long pastDays = (currentTimeStamp - deployTimeStamp) / 1000 / 3600 / 24;

            // 获取总的众筹天数
            Integer totalDays = detailProjectVO.getDay ( );

            // 使用总的众筹天数减去已经过去的天数得到剩余天数
            Integer lastDay = (int)(totalDays - pastDays);

            detailProjectVO.setLastDay (lastDay);
        } catch (ParseException e) {
            e.printStackTrace ( );
        }
        return detailProjectVO;
    }
}
